from django.contrib import messages
from django.shortcuts import render, redirect
from member.models import MerchantUser, PAYMENT_STATUS, Payment
from django.core import serializers

def console(request):
    return render(request, 'main/console.html')


def manage_payment_form(request):
    if request.user.is_authenticated():
        user = request.user
        if not user.is_superuser:
            messages.add_message(request, messages.ERROR, 'User not superUser.')
        payments = Payment.objects.all()
        return render(request, 'main/paymentAdminRequest.html', {'payments': payments, 'PAYMENT_STATUS': PAYMENT_STATUS,})       
    return redirect('index')
    
def payment_pay(request, payment_id):
    if request.user.is_authenticated():
        payment = Payment.objects.get(id=payment_id)
        if payment.status == PAYMENT_STATUS.PAID:
            messages.add_message(request, messages.WARNING, 'This payment was already payed')
            return redirect("manage_payment_form")
        payment.status = PAYMENT_STATUS.PAID
        payment.bank_info_blob = serializers.serialize("json", [payment.merchant.bank])
        payment.save()
        return redirect("manage_payment_form")
    return redirect('index')

def payment_reject(request, payment_id):
    if request.user.is_authenticated():
        payment = Payment.objects.get(id=payment_id)
        payment.status = PAYMENT_STATUS.REJECTED
        payment.rejection_comment = request.POST["reject_comment"]
        payment.save()
        # Give back points to merchant
        merchantUser = payment.merchant
        merchantUser.points = merchantUser.points + payment.amount
        merchantUser.save()
        return redirect("manage_payment_form")
    return redirect('index')